package connect;

import javafx.application.Application;
import javafx.geometry.*;

import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client extends Application {
    //IO 流
    DataOutputStream toServer = null;
    DataInputStream fromServer = null;

    @Override  // 重写Application类的start方法
    public void start(Stage primaryStage) throws Exception {
        //
        BorderPane paneForTextField = new BorderPane();
        paneForTextField.setPadding(new Insets(5,5,5,5));
        paneForTextField.setStyle("-fx-border-color: green");
        paneForTextField.setLeft(new Label("Enter a redius:"));

        TextField textField = new TextField();
        textField.setAlignment(Pos.BOTTOM_RIGHT);
        paneForTextField.setCenter(textField);

        BorderPane mainPane = new BorderPane();
        // 显示内容文本区域
        TextArea textArea = new TextArea();
        mainPane.setCenter(new ScrollPane(textArea));
        mainPane.setTop(paneForTextField);

        // 创建一个场景并放到舞台上
        Scene scene = new Scene(mainPane,450,200);
        primaryStage.setTitle("Client");  // 设置舞台（窗口）的标题
        primaryStage.setScene(scene);  // 把场景放到舞台上
        primaryStage.show(); //展示舞台

        textField.setOnAction(e -> {
            try{
                // 从文本字段获取半径
                double radius = Double.parseDouble(textField.getText().trim());

                // 从服务端发送半径
                toServer.writeDouble(radius);
                toServer.flush();

                // 从服务端获取面积
                double area = fromServer.readDouble();

                textArea.appendText("Readis is "+radius+"\n");
                textArea.appendText("Area received from the server is"+area+"\n");


            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        try {
            // 创建一个socket连接到服务端
            Socket socket = new Socket("localhost",8000);
            // Socket socket = new Socket("ip地址",8000);
            // Socket socket = new Socket("drake.Armstrong.edu",8000);

            // 创建一个输入流从服务端接收数据
            fromServer = new DataInputStream(socket.getInputStream());
            // 创建一个输出流从服务端发送数据
            toServer = new DataOutputStream(socket.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}
